<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="数据库名称" prop="dataSourceName">
        <el-input
          v-model="queryParams.dataSourceName"
          placeholder="请输入数据库名称"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['console:tasks:add']"
          >新增</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['console:tasks:edit']"
          >修改</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['console:tasks:remove']"
          >删除</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['console:tasks:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table
      v-loading="loading"
      :data="list.slice((pgNum - 1) * pgSize, pgNum * pgSize)"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" align="center" />
      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{ (pgNum - 1) * pgSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务编号" align="center" prop="id" />
      <!-- <el-table-column label="数据库" align="center" prop="databaseName" /> -->
      <el-table-column label="数据源" align="center" prop="dataSourceName">
        <template slot-scope="scope">
          <el-button type="text" @click="handleUpdate(scope.row)">{{
            scope.row.dataSourceName
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="center" prop="createBy" />
      <el-table-column label="执行时间" align="center" prop="createTime" />
      <el-table-column label="sql" align="center" prop="sqlContext">
        <template slot-scope="scope">
          <el-button type="text" @click="handleCode(scope.row)"
            >点击查看</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="executeResult">
        <template slot-scope="scope">
          <span
            style="color: #9fe080"
            v-if="toObject(scope.row.executeResult).code == 200"
            >成功</span
          >
          <el-button
            v-else
            type="text"
            style="color: red"
            @click="handleFailError(scope.row)"
            >失败原因</el-button
          >
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['monitor:online:forceLogout']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="pgNum"
      :limit.sync="pgSize"
    />

    <el-dialog
      title="数据源信息"
      width="800px"
      append-to-body
      :visible.sync="NextdataDialog"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="实例名称" prop="dataSourceName">
              <el-input
                v-model="form.dataSourceName"
                placeholder="请输入名称"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="驱动类" prop="driver">
              <el-input
                disabled
                v-model="form.driver"
                placeholder="请输入驱动类"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="IP" prop="ip">
              <el-input disabled v-model="form.ip" placeholder="请输入IP" />
              <span v-if="amountError" style="color: red">{{
                amountError
              }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="端口" prop="port">
              <el-input disabled v-model="form.port" placeholder="请输入端口" />
            </el-form-item>
          </el-col>

          <el-col
            :span="12"
            v-for="item in dict.type.dabase_show"
            :key="item.value"
          >
            <el-form-item
              label="数据库"
              prop="databaseName"
              v-if="item.value == form.type"
            >
              <el-input
                disabled
                v-model="form.databaseName"
                placeholder="请输入数据库"
              />
            </el-form-item>
          </el-col>
          <el-col
            v-for="item in dict.type.instancename_show"
            :key="item.value"
            :span="12"
          >
            <el-form-item
              v-if="item.value == form.type"
              label="实例名"
              prop="schemaName"
            >
              <el-input
                disabled
                v-model="form.schemaName"
                placeholder="请输入数据库实例名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户" prop="uname">
              <el-input
                disabled
                v-model="form.uname"
                placeholder="请输入用户"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="pwd">
              <el-input
                disabled
                type="password"
                v-model="form.pwd"
                placeholder="请输入密码"
                style="width: 270px"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <div style="margin-left: 3px; margin-bottom: 20px">
          高级配置
          <el-switch v-model="showConf" style="margin-left: 10px"> </el-switch>
        </div>
        <el-row v-if="showConf">
          <el-col :span="12">
            <el-form-item label="区分大小写" prop="caseSensitive">
              <el-radio-group disabled v-model="form.caseSensitive">
                <el-radio
                  v-for="dict in dict.type.database_case_sensitive"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="自动提交" prop="autoCommit">
              <el-radio-group disabled v-model="form.autoCommit">
                <el-radio
                  v-for="dict in dict.type.database_auto_commit"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="连接超时" prop="connectTimeout">
              <el-input
                disabled
                v-model="form.connectTimeout"
                placeholder="请输入连接超时"
                onkeyup="value=(value.replace(/\D/g,'')==''?'':parseInt(value))"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="会话超时" prop="socketTimeout">
              <el-input
                disabled
                v-model="form.socketTimeout"
                placeholder="请输入会话超时"
                onkeyup="value=(value.replace(/\D/g,'')==''?'':parseInt(value))"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="编码格式" prop="encoding">
              <el-input
                disabled
                v-model="form.encoding"
                placeholder="请输入编码格式"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Unicode" prop="useUnicode">
              <el-radio-group disabled v-model="form.useUnicode">
                <el-radio label="true">是</el-radio>
                <el-radio label="false">否</el-radio>
                <el-radio label="null">全不选</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="状态" prop="status">
              <el-radio-group disabled v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.data_status"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-form-item label="URL" prop="url">
            <!--  v-for="dict in dict.type.database_auto_commit"
                  :key="dict.value"
            :label="dict.label"-->
            <el-input disabled v-model="form.url" placeholder="请输入URL" />
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item label="备注" prop="remark">
            <el-input
              disabled
              v-model="form.remark"
              type="textarea"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="testConnect">测试连接</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="sql" :visible.sync="dialogStackVisible" width="75%">
      <editor
        @init="editorInit"
        ref="aceEditor"
        v-model="stackErrorsMsg"
        width="100%"
        :height="400"
        lang="sql"
        theme="dracula"
        :options="{
          enableBasicAutocompletion: true,
          enableSnippets: true,
          enableLiveAutocompletion: true,
          showPrintMargin: false, //去除编辑器里的竖线
          tabSize: 4,
          fontSize: 16,
          readOnly: true,
        }"
      />
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogStackVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog title="失败原因" :visible.sync="dialogfailVisible" width="75%">
      <p style="color: red">{{ failError }}</p>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogfailVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { sqlTaskList, sqlTaskDel } from "@/api/console/executeSql";

import {
  listDatasourceInfo,
  getDatasourceInfo,
  databaseCheck,
  updateDatasourceInfo,
} from "@/api/console/datasourceInfo";

export default {
  name: "sqlHistory",
  components: { editor: require("vue2-ace-editor") },
  dicts: [
    "database_case_sensitive",
    "data_status",
    "data_base_type",
    "database_auto_commit",
    "database_datatype",
    "database_datataststatus",
    "dabase_show",
    "instancename_show",
  ],
  data() {
    return {
      rules: {
        dataSourceName: [
          { required: true, message: "请输入实例名称", trigger: "blur" },
        ],
        driver: [{ required: true, message: "请输入驱动类", trigger: "blur" }],
        ip: [{ required: true, message: "请输入ip", trigger: "blur" }],
        port: [{ required: true, message: "请输入端口号", trigger: "blur" }],
        uname: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        pwd: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      NextdataDialog: false,
      data_typeList: [],
      showConf: false,
      form: {},
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      pgNum: 1,
      pgSize: 10,
      // 查询参数
      queryParams: {
        ipaddr: undefined,
        userName: undefined,
        pgNum: 1,
        pgSize: 10,
      },
      dialogStackVisible: false,
      stackErrorsMsg: "",
      failError: "",
      dialogfailVisible: false,
      amountError: "",
      multiple: "",
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    validateAmount() {
      // this.form.url = `jdbc:mysql://${this.form.ip}:${this.form.port}/`;
      if (!this.amountRegex.test(this.form.ip)) {
        this.amountError = "请输入有效的ip";
      } else {
        this.amountError = "";
      }
    },
    submitForm() {
      this.NextdataDialog = false;
    },
    handleDelete(row) {
      let ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除评估任务编号为"' + ids + '"的数据项？')
        .then(function () {
          return sqlTaskDel({ idArray: Array.isArray(ids) ? ids : [ids] });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    testConnect() {
      const {
        type,
        ip,
        port,
        uname,
        pwd,
        databaseName,
        version,
        encoding,
        useUnicode,
        connectTimeout,
        socketTimeout,
        driver,
        url,
      } = this.form;
      databaseCheck({
        type,
        ip,
        port,
        uname,
        pwd,
        databaseName,
        version,
        encoding,
        useUnicode,
        connectTimeout,
        socketTimeout,
        driver,
        url,
      }).then((response) => {
        if (response.data.code == 200) {
          this.$message({
            message: "连接成功",
            type: "success",
          });
          this.form.testStatus = 0;
          this.getList();
        } else {
          this.form.testStatus = 1;
          this.$message.error("连接失败");
          this.getList();
        }
      });
    },
    data_TypeChange(row) {
      row.id = null;
      row.autoCommit = "";
      row.caseSensitive = "";
      row.dataType = this.form.dataType;
      this.form = row;
    },
    handleFailError(row) {
      this.dialogfailVisible = true;
      this.failError = this.toObject(row.executeResult).msg;
    },
    toObject(value) {
      return JSON.parse(value);
    },
    handleUpdate(row) {
      // let ma = row.url.toString();
      // let url = ma.match(/^(.*)@/)
      // this.myurl = `jdbc:${row.type.toLowerCase()}://`;
      // const id = row.id || this.ids;
      // this.myurl = match
      let data = {
        id: row.datasourceId,
      };
      getDatasourceInfo(data).then((response) => {
        this.form = response.data;
        this.NextdataDialog = true;
      });
      let data1 = {
        type: row.type,
        dataType: 1,
      };
      listDatasourceInfo(data1).then((response) => {
        this.data_typeList = response.rows;
      });
      this.reset();
    },
    editorInit() {
      // 初始化
      require("brace/ext/language_tools");
      require("brace/ext/beautify");
      require("brace/ext/error_marker");
      require("brace/ext/searchbox");
      require("brace/ext/split");
      require("brace/snippets/sql");
      require("brace/mode/sql");
      require("brace/theme/dracula");
    },
    /** 查询登录日志列表 */
    getList() {
      this.loading = true;
      sqlTaskList(this.queryParams).then((response) => {
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.pgNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    cancel() {
      this.NextdataDialog = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        dataSourceName: null,
        type: null,
        driver: null,
        ip: null,
        port: null,
        database: null,
        uname: null,
        pwd: null,
        caseSensitive: null,
        autoCommit: null,
        connectTimeout: null,
        socketTimeout: null,
        encoding: null,
        useUnicode: null,
        url: null,
        testStatus: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 强退按钮操作 */
    handleForceLogout(row) {
      this.$modal
        .confirm('是否确认强退名称为"' + row.userName + '"的用户？')
        .then(function () {
          return forceLogout(row.tokenId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("强退成功");
        })
        .catch(() => {});
    },
    handleCode(row) {
      this.dialogStackVisible = true;
      this.stackErrorsMsg = row.sqlContext;
    },
  },
};
</script>
